package com.bwie.filter;

import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @Author: TaoShiHao
 * @Date: 2025/5/21 16:33
 * @Description:
 **/
@Configuration
@Order(-1)
public class MyGlobalFilter implements GlobalFilter {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取参数
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        //获取请求路径
        String url = request.getURI().getPath();
        if(url.contains("/login")){
            System.out.println("白名单:"+url);
            //放行
           return chain.filter(exchange);
        }
        //获取请求头的token
        String token = request.getHeaders().getFirst("token");
        if(token==null){
            System.out.println("token为空:"+url);
            //返回401错误码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        Integer userId = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody().get("userId", Integer.class);
        String tokenKey="token-"+userId;
        String redisKey = stringRedisTemplate.opsForValue().get(tokenKey);
        if(redisKey==null){
            System.out.println("redis的token 为空:"+url);
            //返回401错误码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        if(!token.equals(redisKey)){
            System.out.println("token错误:"+url);
            //返回401错误码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //token续期
        stringRedisTemplate.expire(redisKey,60, TimeUnit.MINUTES);


        //放行
        return chain.filter(exchange);
    }
}
